# Docker 集成测试脚本
# 用于在 CI/CD 环境中运行容器集成测试

# 检查 Docker 是否运行
Write-Host "检查 Docker 环境..." -ForegroundColor Green
try {
    docker --version
    docker info | Out-Null
    Write-Host "Docker 环境正常" -ForegroundColor Green
} catch {
    Write-Host "错误: Docker 未运行或未安装" -ForegroundColor Red
    Write-Host "请确保 Docker Desktop 已安装并启动" -ForegroundColor Yellow
    exit 1
}

# 清理可能存在的测试容器
Write-Host "清理测试环境..." -ForegroundColor Green
docker container prune -f | Out-Null
docker volume prune -f | Out-Null

# 运行快速测试（内存数据库）
Write-Host "运行快速测试..." -ForegroundColor Green
dotnet test --filter "Category!=Container" --verbosity normal --logger "console;verbosity=normal"

if ($LASTEXITCODE -ne 0) {
    Write-Host "快速测试失败" -ForegroundColor Red
    exit $LASTEXITCODE
}

# 检查是否应该运行容器测试
$runContainerTests = $env:RUN_CONTAINER_TESTS -eq "true" -or $args -contains "--container"

if ($runContainerTests) {
    Write-Host "运行容器集成测试..." -ForegroundColor Green
    Write-Host "注意: 这可能需要几分钟时间来下载和启动容器" -ForegroundColor Yellow
    
    # 运行数据库容器测试
    Write-Host "测试数据库容器..." -ForegroundColor Cyan
    dotnet test --filter "FullyQualifiedName~ContainerDatabaseTests" --verbosity normal --logger "console;verbosity=normal"
    
    if ($LASTEXITCODE -ne 0) {
        Write-Host "数据库容器测试失败" -ForegroundColor Red
        exit $LASTEXITCODE
    }
    
    # 运行 Redis 容器测试
    Write-Host "测试 Redis 容器..." -ForegroundColor Cyan
    dotnet test --filter "FullyQualifiedName~RedisIntegrationTests" --verbosity normal --logger "console;verbosity=normal"
    
    if ($LASTEXITCODE -ne 0) {
        Write-Host "Redis 容器测试失败" -ForegroundColor Red
        exit $LASTEXITCODE
    }
    
    # 运行端到端测试
    Write-Host "运行端到端测试..." -ForegroundColor Cyan
    dotnet test --filter "FullyQualifiedName~EndToEndIntegrationTests" --verbosity normal --logger "console;verbosity=normal"
    
    if ($LASTEXITCODE -ne 0) {
        Write-Host "端到端测试失败" -ForegroundColor Red
        exit $LASTEXITCODE
    }
    
    Write-Host "所有容器测试完成!" -ForegroundColor Green
} else {
    Write-Host "跳过容器测试 (使用 --container 参数或设置环境变量 RUN_CONTAINER_TESTS=true 来运行)" -ForegroundColor Yellow
}

# 最终清理
Write-Host "清理测试资源..." -ForegroundColor Green
docker container prune -f | Out-Null

Write-Host "所有测试完成!" -ForegroundColor Green
